package com.sneakxy.mybatis.commons.repository.query.domain.criterions;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.ibatis.scripting.xmltags.SqlNode;
import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.apache.ibatis.session.Configuration;

import com.sneakxy.mybatis.commons.dialect.Dialect;
import com.sneakxy.mybatis.commons.orm.mapping.MybatisColumn;

/**
 * @author 潜行的青衣
 */
public class BetweenCriterion extends AbstractCriterion {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -848217357470546782L;

	/**
	 * @param domainClass
	 * @param property
	 * @param startValue
	 * @param endValue
	 */
	public BetweenCriterion(Class<?> domainClass, String property, Object startValue, Object endValue) {
		super(domainClass, property, new Value(startValue, endValue));
	}
	
	public BetweenCriterion(Class<?> domainClass, String property, Value value) {
		super(domainClass, property, value);
	}

	/* (non-Javadoc)
	 * @see com.sneakxy.mybatis.commons.repository.query.domain.Criterion#toSql(java.lang.String)
	 */
	@Override
	public SqlNode toSql(Configuration config, String operator, String parameterName) {
		Dialect dialet = this.getDialect(config);
		List<MybatisColumn> columns = this.getColumns(config.getTypeHandlerRegistry(), parameterName);
		MybatisColumn column = columns.get(0);
		StringBuilder sqlBuilder = new StringBuilder();
		sqlBuilder.append(operator).append(" ").append(getOpen());
		sqlBuilder.append(dialet.formatColumnName(column.getColumn())).append(" BETWEEN #{");
		sqlBuilder.append(parameterName).append(".start").append("} AND #{");
		sqlBuilder.append(parameterName).append(".end").append("}").append(getClose()).append(" ");
		return new StaticTextSqlNode(sqlBuilder.toString());
	}

	public static class Value implements Serializable {
		
		/**
		 * 
		 */
		private static final long serialVersionUID = 4536544818859362705L;

		private Object start;
		
		private Object end;
		
		public Value(Object start, Object end) {
			this.start = start;
			this.end = end;
		}

		public Object getStart() {
			return start;
		}

		public Object getEnd() {
			return end;
		}

		@Override
		public int hashCode() {
			return new HashCodeBuilder().append(this.start).append(this.end).toHashCode();
		}

		@Override
		public boolean equals(Object obj) {
			if(obj == null) {
				return false;
			}
			if(!(obj instanceof Value)) {
				return false;
			}
			Value value = (Value) obj;
			return new EqualsBuilder()
					.append(this.start, value.start)
					.append(this.end, value.end).isEquals();
		}
		
	}
}
